//
//  EnemySprite.m
//  GameProject
//
//  Created by Blair Trusler on 08/11/2011.
//  Copyright (c) 2011 Blair Trusler. All rights reserved.
//

#import "GameHeader.h"

@implementation EnemySprite

@synthesize walkDownAnim;
@synthesize walkUpAnim;
@synthesize walkLeftAnim;
@synthesize walkRightAnim;


-(void) dealloc{
    [walkUpAnim release];
    [walkDownAnim release];
    [walkLeftAnim release];
    [walkRightAnim release];
    [super dealloc];
}


-(void)changeState:(CharacterStates)newState {
    [self stopAllActions];
    
    id action = nil; 
    CCRepeatForever *repeat;
    repeat = nil;
    
    [self setCharacterState:newState];
    
    switch (newState){
        case kStateWonBattle:
            CCLOG(@"Enemy won the battle!");
            break;

        case kStateDead:
            action = [CCSequence actions:[CCFadeOut actionWithDuration:0.0f],nil];
            CCLOG(@"==Enemy dead");
            return;
        case kStateWalkingDown:
            up = FALSE;
            right = FALSE;
            left = FALSE;
            down = TRUE;
            action = [CCAnimate actionWithAnimation:walkDownAnim restoreOriginalFrame:NO];
            repeat = [CCRepeatForever actionWithAction:action];
            break;
        case kStateWalkingUp:
            up = TRUE;
            right = FALSE;
            left = FALSE;
            down = FALSE;
            action = [CCAnimate actionWithAnimation:walkUpAnim restoreOriginalFrame:NO];
            repeat = [CCRepeatForever actionWithAction:action];
            break;  
        case kStateWalkingLeft:
            up = FALSE;
            right = FALSE;
            left = TRUE;
            down = FALSE;
            action = [CCAnimate actionWithAnimation:walkLeftAnim restoreOriginalFrame:NO];
            repeat = [CCRepeatForever actionWithAction:action];
            break;  
        case kStateWalkingRight:
            up = FALSE;
            right = TRUE;
            left = FALSE;
            down = FALSE;
            action = [CCAnimate actionWithAnimation:walkRightAnim restoreOriginalFrame:NO];
            repeat = [CCRepeatForever actionWithAction:action];
            break;  
        case kStateIdle:
            CCLOG(@"Enemy Changing State - Idle");
            repeat = nil;
            if (left == TRUE){
                [self setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"E2Left2.png"]]; 
            }
            if (right == TRUE){
                [self setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"E2Right2.png"]]; 
            }
            if (up == TRUE){
                [self setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"E2Up2.png"]]; 
            }
            if (down == TRUE){
                [self setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"E2Down2.png"]]; 
            }
            
            break;
            
        case kStateCollision:
            CCLOG(@"ENEMY kStateCOLLISION");

            break;
            
        case kStateEnemyPatrol:
            CCLOG(@"Enemy idle for over 5 seconds, patrolling.");
            
            float xPositionOffSet = 50.0f;
            float yPositionOffSet = 25.0f;
            
            id counterReset = [CCCallFunc actionWithTarget:self selector:@selector(counterTickReset)];

            if (i>=1)  {
                action = [CCSequence actions:[CCAnimate actionWithAnimation:walkDownAnim restoreOriginalFrame:NO],[CCMoveTo actionWithDuration:0.8f position:originalPos], [counterReset copy], nil];
                
            }
            
            else {
                id direction = [CCCallFunc actionWithTarget:self selector:@selector(setEnemyDirection)];

                if (down == TRUE){
                    action = [CCSequence actions:[CCAnimate actionWithAnimation:walkDownAnim restoreOriginalFrame:NO],[CCMoveTo actionWithDuration:0.2f position:ccp([self position].x, [self position].y - yPositionOffSet)],[direction copy], nil];
                }
                if (up == TRUE){
                    action = [CCSequence actions:[CCAnimate actionWithAnimation:walkUpAnim restoreOriginalFrame:NO],[CCMoveTo actionWithDuration:0.2f position:ccp([self position].x, [self position].y + yPositionOffSet)],[direction copy], nil];
                }
                if (right == TRUE){
                    action = [CCSequence actions:[CCAnimate actionWithAnimation:walkRightAnim restoreOriginalFrame:NO],[CCMoveTo actionWithDuration:0.4f position:ccp([self position].x + xPositionOffSet, [self position].y)],[direction copy], nil];
                }
                if (left == TRUE){
                    action = [CCSequence actions:[CCAnimate actionWithAnimation:walkLeftAnim restoreOriginalFrame:NO],[CCMoveTo actionWithDuration:0.4f position:ccp([self position].x - xPositionOffSet, [self position].y)],[direction copy], nil];
                }
            }
            
            break;
            
        case kStateEnemyChase:
            CCLOG(@"Detected");            

            break;
            
    }    
    
    if ((repeat!=nil)&&(action!=nil)){
        [self runAction:repeat];        //Loops animation 
    }
    
    if ((action != nil)&&(repeat == nil)) {
        [self runAction:action];
    }
}

-(void)counterTickReset{
    i=0;
}

-(void)setEnemyDirection{
    if (down == TRUE){
        up = FALSE;
        right = TRUE;
        left = FALSE;
        down = FALSE;
    }
    else if (up == TRUE){
        up = FALSE;
        right = FALSE;
        left = TRUE;
        down = FALSE;
    }
    else if (right == TRUE){
        up = TRUE;
        right = FALSE;
        left = FALSE;
        down = FALSE;
    }
    else if (left == TRUE){
        up = FALSE;
        right = FALSE;
        left = FALSE;
        down = TRUE;
    }
}

-(CGRect)greaterBoundingBox1{
    CGRect enemyAgroBoundingBox;
    CGRect enemyBoundingBox = [self adjustedBoundingBox];
    //Creates bounding box 5 times larger than before (around top & right hand side of sprite):
    enemyAgroBoundingBox = CGRectMake(enemyBoundingBox.origin.x, enemyBoundingBox.origin.y, enemyBoundingBox.size.width*0.2f, enemyBoundingBox.size.height*0.2f);
    return enemyAgroBoundingBox;
}

-(CGRect)greaterBoundingBox2{
    CGRect enemyAgroBoundingBox2;
    CGRect enemyBoundingBox = [self adjustedBoundingBox];
    //Creates bounding box 5 times larger than before (around bottom & left hand side of sprite):
    enemyAgroBoundingBox2 = CGRectMake(enemyBoundingBox.origin.x, enemyBoundingBox.origin.y, enemyBoundingBox.size.width*-0.2f, enemyBoundingBox.size.height*-0.2f);
    
    return enemyAgroBoundingBox2;
}

-(void)updateStateWithDeltaTime:(ccTime)deltaTime andListOfGameObjects:(CCArray*)listOfGameObjects {

    if (characterState == kStateDead){
        CCLOG(@"Enemy Sprite Dead");
        [self setVisible:NO];
        [self removeFromParentAndCleanup:YES];
        return;
    }
    
    enemyCharacter = (GameCharacter*)[[self parent] getChildByTag:kPlayerSpriteTagValue];                    
    
    CGRect playerBoundingBox = [enemyCharacter adjustedBoundingBox];        
    if (CGRectIntersectsRect([self adjustedBoundingBox], playerBoundingBox)){
        CCLOG(@"collision with enemy!");
        [AudioManager gameOverSound];
        [[SceneManager sharedSceneManager] runSceneWithID:kGameOverScene];     //Objective reached, load "level complete" scene

    }
    
    if (CGRectIntersectsRect([self greaterBoundingBox1], playerBoundingBox)){
        CCLOG(@"collision with enemy!");
        [AudioManager gameOverSound];
        [[SceneManager sharedSceneManager] runSceneWithID:kGameOverScene];     //Objective reached, load "level complete" scene
    }
    
    if (CGRectIntersectsRect([self greaterBoundingBox2], playerBoundingBox)){
        CCLOG(@"collision with enemy!");
        [AudioManager gameOverSound];
        [[SceneManager sharedSceneManager] runSceneWithID:kGameOverScene];     //Objective reached, load "level complete" scene
    }    
    
    
    
    
    if (characterState == kStateIdle){
        //move after time?
    }
    if ([self numberOfRunningActions] == 0) {
        //no animation running
        
        if (self.characterState == kStateIdle) {
            msIdle = msIdle + deltaTime;
            if (msIdle > kEnemyIdleTimer) {  //UNCOMMENT THIS IN TO PATROL AGAIN:
                //[self changeState:kStateEnemyPatrol];  //used to be kStateEnemyPatrol    - IMPORTANT NOTE! 
            }
        } else if (self.characterState != kStateIdle){
            msIdle = 0.0f;
            
            [self changeState:kStateIdle];
        }
    }
}



-(void)initAnimations {
    [self setWalkDownAnim:[self loadPlistForAnimationWithName:@"walkAnimDown" andClassName:NSStringFromClass([self class])]];
    
    [self setWalkUpAnim:[self loadPlistForAnimationWithName:@"walkAnimUp" andClassName:NSStringFromClass([self class])]];
    
    [self setWalkLeftAnim:[self loadPlistForAnimationWithName:@"walkAnimLeft" andClassName:NSStringFromClass([self class])]];
    
    [self setWalkRightAnim:[self loadPlistForAnimationWithName:@"walkAnimRight" andClassName:NSStringFromClass([self class])]];
}

- (id)init{
    if( (self=[super init]) ) {
        CCLOG(@"### Enemy Sprite initialized");
        i=0;
        down=TRUE;
        [self initAnimations];
        msIdle = 0.0f;
        gameObjectType = kEnemyType1; 
        originalPos = kEnemySpawnLocation1; 
        [self changeState:kStateIdle]; 

        CCLOG(@"Enemy1 Spawn Location:%@",NSStringFromCGPoint(kEnemySpawnLocation1));
    }
    return self;
}

@end



